//
//  Layout.m
//  123123
//
//  Created by 张钧 on 2017/5/3.
//  Copyright © 2017年 JinYun. All rights reserved.
//

#import "Layout.h"
@interface Layout ()
@property(nonatomic,copy)Block block;
@property(nonatomic,strong)NSMutableArray * arrHeight;//存放高度
@property(nonatomic,strong)NSMutableArray * arrAttribute;//存放属性

@end
@implementation Layout
-(instancetype)init
{
    if (self==[super init]) {
        //默认设置   1.存放高度  2.存放属性 3.行间距  4.列间距  5.行数  6.边距
        _arrHeight=[NSMutableArray array];
        _arrAttribute=[NSMutableArray array];
        _rowSpacing=10;
        _lineSpacing=10;
        _num=3;
        _insets=UIEdgeInsetsMake(10, 10, 10, 10);
    }
    return self;
}
-(void)prepareLayout
{
    [super prepareLayout];
    //清空数据
    [_arrHeight removeAllObjects];
    //存放初始高度
    for (int i=0; i<_num; i++) {
        [_arrHeight addObject:@(_insets.top)];
    }
    [_arrAttribute removeAllObjects];
    //获取每个item的属性
    NSInteger itemCount=[self.collectionView numberOfItemsInSection:0];
    for (int i=0; i<itemCount; i++) {
        UICollectionViewLayoutAttributes * attributes=[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        
        [_arrAttribute addObject:attributes];
    }
    
}
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return _arrAttribute;
}
//最大
-(CGSize)collectionViewContentSize
{
    CGFloat maxHeight=[_arrHeight[0]floatValue];
    
    for (int i=1; i<_num; i++) {
        if (maxHeight <[_arrHeight[i]floatValue]) {
            maxHeight=[_arrHeight[i]floatValue];
        }
    }
    return CGSizeMake(0, maxHeight);
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes * arrtribute=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    CGFloat Cw=self.collectionView.frame.size.width;
    CGFloat cellWidth= ((Cw - _insets.left - _insets.right) - (_num - 1) * _lineSpacing) / _num;//宽度
    
    CGFloat cellHeight=0;
    if (self.block) {
        cellHeight=self.block(indexPath,cellWidth);
    }
    
    //横坐标
    CGFloat minHeight=[_arrHeight[0]floatValue];
    
    int lineNum=0;
    //最小
    for (int i=1; i<_num; i++) {
        if (minHeight >[_arrHeight[i]floatValue]) {
            minHeight=[_arrHeight [i]floatValue];
            lineNum=i;

        }
    }
    CGFloat cellX=_insets.left+(cellWidth +_lineSpacing)*lineNum;//宽度
    CGFloat cellY=[_arrHeight[lineNum]floatValue]+_lineSpacing;
    //尺寸
    arrtribute.frame=CGRectMake(cellX, cellY, cellWidth, cellHeight);
    //刷新数组数据
    self.arrHeight[lineNum]=@(cellY+cellHeight);
    
    return arrtribute;
}

-(void)backHeight:(CGFloat (^)(NSIndexPath *, CGFloat))block
{
    if (self.block!=block) {
        self.block=block;
    }
}
@end
